package builder

import (
	"os"
	"path/filepath"
	"testing"
)

// 测试辅助结构体
type testHelper struct {
	t         *testing.T
	tempDirs  []string
	tempFiles []string
}

// 创建测试辅助对象
func newTestHelper(t *testing.T) *testHelper {
	return &testHelper{
		t:         t,
		tempDirs:  make([]string, 0),
		tempFiles: make([]string, 0),
	}
}

// 创建测试构建配置
func (h *testHelper) createTestBuildConfig() *BuildConfig {
	workDir := h.createTempDir()
	cacheDir := h.createTempDir()

	return &BuildConfig{
		ServiceName:  "test-service",
		WorkDir:     workDir,
		CacheDir:    cacheDir,
		BuildTool:   BuildToolMaven,
		JDKVersion:  "8",
		SkipTests:   true,
		ImageName:   "test-image",
		ImageTag:    "latest",
		DockerMirror: "docker.io/library",
		CPULimit:    "1",
		MemoryLimit: "1024M",
	}
}

// 断言目录存在
func (h *testHelper) assertDirExists(path string) {
	info, err := os.Stat(path)
	if err != nil {
		h.t.Fatalf("Directory %s does not exist: %v", path, err)
	}
	if !info.IsDir() {
		h.t.Fatalf("Path %s is not a directory", path)
	}
}

// 断言文件存在
func (h *testHelper) assertFileExists(path string) {
	info, err := os.Stat(path)
	if err != nil {
		h.t.Fatalf("File %s does not exist: %v", path, err)
	}
	if info.IsDir() {
		h.t.Fatalf("Path %s is a directory, expected file", path)
	}
}

// 断言路径不存在
func (h *testHelper) assertNotExists(path string) {
	_, err := os.Stat(path)
	if err == nil {
		h.t.Fatalf("Path %s exists, expected not to exist", path)
	}
	if !os.IsNotExist(err) {
		h.t.Fatalf("Unexpected error checking path %s: %v", path, err)
	}
}

// 创建临时目录
func (h *testHelper) createTempDir() string {
	dir, err := os.MkdirTemp("", "test-*")
	if err != nil {
		h.t.Fatalf("Failed to create temp dir: %v", err)
	}
	h.tempDirs = append(h.tempDirs, dir)
	return dir
}

// 创建临时文件
func (h *testHelper) createTempFile() string {
	file, err := os.CreateTemp("", "test-*")
	if err != nil {
		h.t.Fatalf("Failed to create temp file: %v", err)
	}
	path := file.Name()
	file.Close()
	h.tempFiles = append(h.tempFiles, path)
	return path
}

// 复制测试项目
func (h *testHelper) copyTestProject(targetDir string) {
	// 创建测试项目结构
	dirs := []string{
		filepath.Join(targetDir, "src", "main", "java"),
		filepath.Join(targetDir, "src", "test", "java"),
	}

	for _, dir := range dirs {
		if err := os.MkdirAll(dir, 0755); err != nil {
			h.t.Fatalf("Failed to create directory %s: %v", dir, err)
		}
	}

	// 创建测试文件
	files := map[string]string{
		filepath.Join(targetDir, "pom.xml"): `<?xml version="1.0" encoding="UTF-8"?>
<project>
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.example</groupId>
    <artifactId>test-project</artifactId>
    <version>1.0.0</version>
</project>`,
		filepath.Join(targetDir, "src", "main", "java", "Application.java"): `
public class Application {
    public static void main(String[] args) {
        System.out.println("Hello, World!");
    }
}`,
		filepath.Join(targetDir, "src", "test", "java", "ApplicationTest.java"): `
public class ApplicationTest {
    @Test
    public void testMain() {
        // Test implementation
    }
}`,
	}

	for path, content := range files {
		if err := os.WriteFile(path, []byte(content), 0644); err != nil {
			h.t.Fatalf("Failed to write file %s: %v", path, err)
		}
	}
}

// 检查Docker可用性
func (h *testHelper) checkDocker() bool {
	_, err := os.Stat("/var/run/docker.sock")
	return err == nil
}

// 清理临时文件和目录
func (h *testHelper) cleanup() {
	// 清理临时文件
	for _, file := range h.tempFiles {
		if err := os.Remove(file); err != nil && !os.IsNotExist(err) {
			h.t.Errorf("Failed to remove temp file %s: %v", file, err)
		}
	}

	// 清理临时目录
	for _, dir := range h.tempDirs {
		if err := os.RemoveAll(dir); err != nil && !os.IsNotExist(err) {
			h.t.Errorf("Failed to remove temp dir %s: %v", dir, err)
		}
	}
}
